<?php
/**
 * Created by PhpStorm.
 * User: 那时年少
 * Date: 2017/3/14
 * Time: 22:14
 */

namespace NewCome\Controller;

use NewCome\Model\UserModel;
use NewCome\Object\TaskObject;
use NewCome\Object\UserObject;

class IndexController
{
    function index(){
        $doc = new \Document();
//        $doc->loadPDM('./Doc/new.pdm');
//        $doc->generateControllers()->generateModels()->generateObjects();
        $doc->autoFinishControllerByObject(new UserObject());
        //$doc->autoFinishControllerByObject(new TaskObject());
    }

    public function userLogin()
    {
        $message = '';
        $user = M('user');
        $name_db = $user->where(['name' => $_POST['username']])->find();
        $password_db = $user->where(['password' => $_POST['password']])->find();
        if (empty($_POST['username'])) {
            $message .= '输入用户不能为空';
        } elseif (empty($_POST['password'])) {
            $message .= '输入密码不能为空';
        } elseif ($_POST['username'] != $name_db['name']) {
            $message .= '输入用户名错误';
        } elseif ($_POST['password'] != $password_db['password']) {
            $message .= '输入密码错误';
        } else {
            $_SESSION['name'] = $_POST['username'];
            $_SESSION['password'] = $_POST['password'];
        }

        if ($message != null) {
            echo $message;
        } else {
            echo '登陆成功';
        }
    }

    public function register()
    {
        $message = '';
        $array = array();
        $user = M('user');
        $login = $this->check($_POST['username']);
        if (empty($_POST['username'])) {
            $message .= '用户输入不能为空';
        }elseif($login == false){
            $message .= '该用户名已经存在，请重新输入';
        } elseif (strlen($_POST['username']) < 4) {
            $message .= '用户格式不正确';
        } elseif (empty($_POST['password'])) {
            $message .= '密码输入不能为空';
        } elseif (strlen($_POST['password']) < 4) {
            $message .= '密码输入格式不真确';
        } else {
            $array['name'] = $_POST['username'];
            $array['password'] = $_POST['password'];
        }

        if ($message != null) {
            echo $message;
        } else {

            if ($user->add($array)) {
                echo '注册成功';
            } else {
                echo '注册失败';
            }
        }
    }
    public function check($name)
    {
        $user = M('user');
        $t = $user->where(['name' => $name])->find();
        if (false != $t) {
            return false;
        } else {
            return true;
        }
    }
}